package com.zgc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zgc.common.BaseContext;
import com.zgc.common.R;
import com.zgc.dto.OrderDto;
import com.zgc.entity.Category;
import com.zgc.entity.OrderDetail;
import com.zgc.entity.Orders;
import com.zgc.service.OrderDetailService;
import com.zgc.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    /**
     * 用户下单
     * @param orders
     * @return
     */
    @Autowired
    private OrderDetailService orderDetailService;
    @PostMapping("/submit")
    public R<Long> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        Long orderId=orderService.submit(orders);
        return R.success(orderId);
    }
    //前端分页查询
    @GetMapping("/userPage")
    public R<Page> userPage(Long page, Long pageSize) throws ParseException {
        Page pageInfo=new Page(page,pageSize);
        //分页对象构建
        Page<Orders> pageinfo= new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        lambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(pageinfo,lambdaQueryWrapper);
        //新的page
        Page<OrderDto> pageDto=new Page<OrderDto>(page,pageSize);
        BeanUtils.copyProperties(pageinfo,pageDto,"records");
        List<Orders> records = pageinfo.getRecords();
        List<OrderDto> list=records.stream().map((item)->{
            OrderDto orderDto=new OrderDto();
            BeanUtils.copyProperties(item,orderDto);
            Long orderId=item.getId();
            //根据orderId查询对应的数据
            LambdaQueryWrapper<OrderDetail> lw=new LambdaQueryWrapper<>();
            lw.eq(OrderDetail::getOrderId,orderId);
            List<OrderDetail> list1 = orderDetailService.list(lw);
            orderDto.setOrderDetails(list1);
            return orderDto;
        }).collect(Collectors.toList());
        pageDto.setRecords(list);
        return R.success(pageDto);
    }
}


